package pl.peterjack.servlet.dane.pracownicy;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import pl.peterjack.model.PMF;
import pl.peterjack.model.dane.Firma;
import pl.peterjack.model.dane.Pracownik;
import pl.peterjack.model.dane.PracownikUprawnienia;
import pl.peterjack.model.dane.RezultatOdpowiedz;

import com.google.appengine.api.datastore.Key;
import com.google.gson.Gson;

public class UprawnienieLista extends HttpServlet {
	
	Log log = new LogFactoryImpl().getInstance( getClass() );

	@SuppressWarnings("unchecked")
	@Override 
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		{
			Pracownik pracownik = (Pracownik) req.getSession().getAttribute("firma_pracownik");
			if (req.getSession().getAttribute("firma_klient") != null || pracownik != null) {
				req.getSession().invalidate();
				resp.setContentType("text/plain");
				resp.setStatus(resp.SC_MOVED_TEMPORARILY);
				resp.setHeader("Location", "/");
				return;
			}
		}
		RezultatOdpowiedz result = new RezultatOdpowiedz();
		try {
		    Firma firma = (Firma) req.getSession().getAttribute("firma");
		    List<PracownikUprawnienia> results = null;
		    Query query = pm.newQuery(PracownikUprawnienia.class, "firma == firmaPodana");
			query.declareParameters(Key.class.getName() + " firmaPodana");
			results = (List<PracownikUprawnienia>) query.execute(firma.getId()); 
		    result.setData( results  );
			result.setSuccess(true); 
		    Gson gson = new Gson();
		    //resp.setContentType("application/json");
		    resp.setCharacterEncoding("UTF-8");
	        resp.getWriter().println("{\"items\":"+gson.toJson(results)+"}");
		} catch (Exception e) { 
			log.error(e);
			result.setSuccess(false);
		} finally {
            pm.close();
        }
	}

}	

